"use strict";
const mongoose = require("mongoose");
const tool = require("../utils/tool");
const _ = require("lodash");
const moment = require("moment");
const config = require("../config");

async function validateUserAuth (atworkInstance, userId) {
  // isAdminOfThisApp方法传空字符，返回全部管理员
  const admins = await atworkInstance.isAdminOfThisApp("");
  const isAdmin = admins.result.records.find(user => {
    return user.user_id == userId;
  });
  return isAdmin
    ? true
    : false;
}

async function validateUserTicket(req) {
  const atworkInstance = tool.getAtworkInstance(req.body);
  const user = await atworkInstance.validateUserTicket(req.body.ticket, req.body.userId);
  user.isAdmin = await validateUserAuth(atworkInstance, user.user_id);
  if(!user.isAdmin){
    throw new Error("e_not_admin");
  }
  return user;
};

async function regenSession(req) {
  return new Promise((success, fail) => {
    req.session.regenerate(function(e) {
      if (e) {
        console.error("重新生成sid失败", e);
        fail(new Error("e_session"));
      } else {
        console.log("重新生成sid成功");
        success();
      }
    });
  });
};

const setSeesion = (req, workplusUser) => {
  req.session.account = {
    domainId: workplusUser.domain_id,
    orgId: workplusUser.org_id,
    userId: workplusUser.user_id,
    name: workplusUser.name,
    pinyin: workplusUser.pinyin,
    username: workplusUser.username,
    positions: workplusUser.positions,
    nickname: workplusUser.nickname,
    isAdmin: workplusUser.isAdmin,
    avatar: workplusUser.avatar
  };
}

const logout = function(req, res) {
  const client = tool.getResponseFunc(res);
  req.session.destroy(e => {
    if (e) {
      console.error("销毁session失败", e);
      client.fail(new Error("e_session"));
    } else {
      console.log("销毁session成功");
      client.success();
    }
  });
};

const enhanceSetHeader = (res) => {
  const extractSid = (rawSid) => {
    const reg = /connect.sid=[^;]*?;/;
    const result = rawSid.match(reg);
    if (!result) {
      console.error("未找到sid", rawSid);
      return "";
    } else {
      return result[0];
    }
  };
  //这个操蛋的hack是为了将加了签名的set-cookie返回给客户端，因为蛋疼的ios上需要它来伪造session访问
  const origSetHeader = res.setHeader;
  res.setHeader = function(key, value) {
    origSetHeader.call(res, key, value);
    const keyOfCookie = "set-cookie";
    if (key === keyOfCookie) {
      res.setHeader("fuckTheIOS", extractSid(res._headers[keyOfCookie][0]));
    }
  };
};

const transStyles = (workplusUser)=>{
  return {
    domainId: workplusUser.domain_id,
    orgId: workplusUser.org_id,
    userId: workplusUser.user_id,
    name: workplusUser.name,
    pinyin: workplusUser.pinyin,
    username: workplusUser.username,
    positions: workplusUser.positions,
    nickname: workplusUser.nickname,
    isAdmin: workplusUser.isAdmin,
    avatar: workplusUser.avatar
  }
}

async function login(req, res) {
  const client = tool.getResponseFunc(res);
  try {
    enhanceSetHeader(res);
    const workplusUser = await validateUserTicket(req);
    setSeesion(req, workplusUser);
    const user = transStyles(workplusUser);
    // 只有移动端才用到jwt，1、移动端才能重新获取ticket 2、ios端cookie有问题，跳转到其它链接会把cookie刷掉
    // const jwtToken = jwt.sign(req.session.account, config.privateConfig.clientId);
    // user.token = jwtToken;
    client.success(user);
  } catch (e) {
    console.error("登陆失败", e);
    client.fail(e);
  };
};

module.exports = {
  login,
  logout,
}
